/***************************************************************************
  * 
  * Homework for chapter 5 -- Acoustic Echo Cancellation
  *
  * Here is the realization of Time Delay Estimation api. 
  *
  **************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dios_ssp_tde.h"
#include "dios_ssp_share_rfft.h"

/**
 * @brief tde process
 *
 * You are going to finish this function of TDE, dios_ssp_tde().
 * Obviously the time delay is within [0, inputdata_length).
 * Since we don't know the ground truth delay, we usually need 
 * a longer buffer for TDE. In this lab we use about 1s buffer
 * for TDE. You can apply GCC method to estimate the time delay
 * between input signal and reference signal. 
 *
 * @param inputdata          input data buffer.
 * @param refdata            reference data buffer.
 * @param inputdata_length   input data length (samples), also the reference data length.
 * @return                   estimated time delay (samples) between input signal and reference signal.
 */
int dios_ssp_tde(short* inputdata, short* refdata, long int inputdata_length)
{
    int delay = 0;
    
    // please finish your code here...

    // convert to float
    float inputdata_f[inputdata_length], refdata_f[inputdata_length];
    for (int i = 0; i < inputdata_length; ++i) {
        inputdata_f[i] = inputdata[i]/ 32768.0;
        refdata_f[i] = refdata[i]/ 32768.0;
    }
    // fftshift(ifft(fft(x1,NFFT).*conj(fft(x2,NFFT))))

    float inputdata_fft[inputdata_length], refdata_fft[inputdata_length],
            times_fft[inputdata_length], times_ifft[inputdata_length];

    void *rfft_handle = dios_ssp_share_rfft_init(512);
    dios_ssp_share_rfft_process(rfft_handle, inputdata_f, inputdata_fft);
    dios_ssp_share_rfft_process(rfft_handle, refdata_f, refdata_fft);
    for (int i = 0; i < inputdata_length; ++i) {
        times_fft[i] = inputdata_fft[i] * refdata_fft[i];
    }

    dios_ssp_share_irfft_process(rfft_handle, times_fft, times_ifft);

//    int delay = 0;
    for (int i = 1; i < inputdata_length; ++i) {
        if(times_ifft[i] > times_ifft[delay] ){
            delay = i;

        }
    }


    // end TDE
    
    return delay;
}

